/*
 * Stringify.c : convert a binary file (usually PNG or JPEG) into a c-string so
 * that it can be directly parsed by SIT GFX_LoadImage() as inline data.
 *
 * Will only generate target file if it is older than source file. You can
 * thus use this tool a pre-built step for IDE like Code::Blocks.
 *
 * Written by T.Pierron, Apr 2010.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "UtilityLib.h"

int main(int nb, char * argv[])
{
	if (nb < 3)
	{
		fprintf(stderr, "usage: %s <file-in> <file-out>\n", *argv);
		return 1;
	}

	#ifndef	DEBUG
	if (TimeStamp(argv[1], 2) <= TimeStamp(argv[2], 2))
		return 0;
	#endif

	FILE * in  = fopen(argv[1], "rb");
	FILE * out = fopen(argv[2], "wb");

	if (in && out)
	{
		TEXT buffer[512];
		int  chr = 7, nbc, last = 0;

		fprintf(out, "\"data://");
		/* 4 bytes for file size - big endian format */
		nbc = FileSize(argv[1]);
		buffer[3] = nbc & 0xff; nbc >>= 8;
		buffer[2] = nbc & 0xff; nbc >>= 8;
		buffer[1] = nbc & 0xff; nbc >>= 8;
		buffer[0] = nbc & 0xff; nbc = 4;

		do {
			DATA8 p;
			for (p = buffer; nbc > 0; nbc --, p ++)
			{
				TEXT hex[8];

				if (last > 0 && isxdigit(*p)) chr += fprintf(out, "\"\""); last = 0;
				if (chr == 0)   chr += fprintf(out, "\n\"");
				if (*p == 0)    chr += fprintf(out, "\\0"); else
				if (*p == '\n') chr += fprintf(out, "\\n"); else
				if (*p == '\"') chr += fprintf(out, "\\\""); else
				if (*p == '\\') chr += fprintf(out, "\\\\"); else
				if (*p == '\t') chr += fprintf(out, "\\t"); else
				if (*p < 32 || strchr("\x81\x8d\x8f\x90\x9d", *p))
				{
					sprintf(hex, "\\x%02x", *p); last = hex[3];
					fputs(hex, out); chr += 4;
				}
				else fputc(*p, out), chr ++;

				if (chr >= 80) fprintf(out, "\""), chr = last = 0;
			}
		}
		while ((nbc = fread(buffer, 1, sizeof buffer, in)) > 0);

		if (chr > 0) fputc('\"', out);
		fprintf(out, ";\n");
	}
	if (out) fclose(out);
	if (in)  fclose(in);

	return 0;
}
